/**
 * 
 */
package com.csair.youth.web.action;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.csair.youth.constant.Constant;
import com.csair.youth.database.Resource;
import com.csair.youth.database.SysConfig;
import com.csair.youth.database.User;
import com.csair.youth.service.impl.CategoryServiceImpl;
import com.csair.youth.service.impl.ResourceServiceImpl;
import com.csair.youth.service.impl.SysConfigServiceImpl;
import com.csair.youth.service.impl.UserServiceImpl;

/**
 * @author mickey
 *
 */
public class FileUploadAction extends _BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8389985087439478783L;
	
	private static final Logger log = Logger.getLogger(FileUploadAction.class);

	private File upload;
	private String uploadFileName;
	private String uploadContentType;
	
	private Resource item;
	private UserServiceImpl userService;
	private ResourceServiceImpl resourceService;
	private SysConfigServiceImpl sysConfigService;
	private CategoryServiceImpl categoryService;
	
	private String treeString;
	
	public Resource getItem() {
		return item;
	}
	public void setItem(Resource item) {
		this.item = item;
	}
	public UserServiceImpl getUserService() {
		return userService;
	}
	public void setUserService(UserServiceImpl userService) {
		this.userService = userService;
	}
	public ResourceServiceImpl getResourceService() {
		return resourceService;
	}
	public void setResourceService(ResourceServiceImpl resourceService) {
		this.resourceService = resourceService;
	}
	public SysConfigServiceImpl getSysConfigService() {
		return sysConfigService;
	}
	public void setSysConfigService(SysConfigServiceImpl sysConfigService) {
		this.sysConfigService = sysConfigService;
	}
	public CategoryServiceImpl getCategoryService() {
		return categoryService;
	}
	public void setCategoryService(CategoryServiceImpl categoryService) {
		this.categoryService = categoryService;
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String getTreeString() {
		return treeString;
	}
	public void setTreeString(String treeString) {
		this.treeString = treeString;
	}
	
	public String execute(){
		treeString = categoryService.buildCategoryTreeString(categoryService.buildCategoryTree(null, false).get("ROOT"), "categoryTree", "javascript:setCategory(this, \"categoryTree\");");
		return SUCCESS;
	}
	
	public String doUpload(){
		if(!validInput(item, upload)){
			return INPUT;
		}
		if(StringUtils.isNotEmpty(item.getId())) item.setId(null);   //只允许上传新文件
		String userId = (String)this.getSessionAttribute(Constant.USER_ID_SESSION_KEY);
		User user = userService.getUser(userId);
		String enableIps = user.getEnableIp();
		String ips[] = enableIps.split(";");
		if(ips == null) {
			this.setMessage("你不能上传文件，没有允许的IP列表，请联系管理员.");
			return INPUT;
		}
		String currentIp = this.getServletRequest().getRemoteAddr();
		boolean isIpCorret = false;
		for(int i=0; i<ips.length; i++){
			if(currentIp.equals(ips[i])){
				//通过IP验证
				isIpCorret = true;
				break;
			}
		}
		if(!isIpCorret) {
			this.setMessage("你的IP不在允许的IP列表之内，不允许上传文件.");
			return INPUT;
		}
		File tmpDir = resourceService.getTmpPath();
		if(tmpDir == null){
			this.setMessage("获取上传目录出错,请重试.");
			return INPUT;
		}
		if(StringUtils.isEmpty(item.getFileName())){
			item.setFileName(uploadFileName);
		}
		item.setContentType(uploadContentType);
		String destPath = null;
//		String ext = ".tmp";
//		if(uploadFileName.lastIndexOf(".")>0){
//			ext = uploadFileName.substring(uploadFileName.lastIndexOf("."));
//		}
		try {
			destPath = tmpDir.getCanonicalPath()+File.separator+System.currentTimeMillis()+"_"+uploadFileName;
			resourceService.copyFile(upload, destPath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("复制文件到临时目录出错!文件:"+uploadFileName);
			this.setMessage("上传文件过程发生错误[1],请重试.");
			return INPUT;
		}
		item.setAbsolutePath(destPath);
		item.setDownloadTimes(0);
		item.setUploadUserId((String)this.getSessionAttribute(Constant.USER_ID_SESSION_KEY));
		item.setUploadIp(currentIp);
		item.setUploadTime(new Date());
		item.setAuditResult(Constant.RESOURCE_AUDIT_WAIT);
		item.setLastModifyTime(item.getUploadTime());
		item.setHttpDownAddress("");
		item.setFtpDownAddress("");
		resourceService.saveResource(item);
		
		//发送email
		SysConfig config = sysConfigService.getSysConfigByKey(Constant.SERVER_IP_PORT_KEY);
		String serverIpPort = null;
		if(config == null){
			serverIpPort = "http://127.0.0.1:8080/youth";
		}
		else{
			serverIpPort = config.getConfigValue();
		}
		String auditUrl = serverIpPort+(serverIpPort.endsWith("/")?"":"/")+"ResourceAudit.action";
		resourceService.notifyAuditorsByEmail(item, auditUrl);
		
		this.setMessage("已成功上传文件,请等待审核.");
		return SUCCESS;
	}
	
	private boolean validInput(Resource item, File upload){
		if(item == null || upload == null){
			this.setMessage("资源对象为空或未选择上传文件");
			return false;
		}
		boolean allValid = true;
		StringBuffer msgBf = new StringBuffer();
//		String name = item.getFileName();
//		if(StringUtils.isEmpty(name) || StringUtils.length(name)> 100){
//			msgBf.append("资源名不能为空且必须在100个字符内<br/>");
//			allValid = false;
//		}
		String fileName = item.getFileName();
		if(!StringUtils.isEmpty(fileName) && StringUtils.length(fileName)> 100){
			msgBf.append("文件名必须在100个字符内<br/>");
			allValid = false;
		}
		String desc = item.getDescription();
		if(!StringUtils.isEmpty(desc) && StringUtils.length(desc)> 120){
			msgBf.append("资源描述必须在120个字符内<br/>");
			allValid = false;
		}
		String categoryId = item.getCategoryId();
		if(StringUtils.isEmpty(categoryId) || categoryService.getCategory(categoryId) == null){
			msgBf.append("必须选择一个分类<br/>");
			allValid = false;
		}
		this.setMessage(msgBf.toString());
		return allValid;
	}
}
